package com.hao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hao.dto.DailyStatisticsDTO;
import com.hao.entity.SensorData;
import com.hao.mapper.SensorDataMapper;
import com.hao.service.StatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 数据统计服务实现类
 */
@Slf4j
@Service
public class StatisticsServiceImpl implements StatisticsService {
    
    @Autowired
    private SensorDataMapper sensorDataMapper;
    
    @Override
    public DailyStatisticsDTO getDailyStatistics(String date) {
        DailyStatisticsDTO statistics = new DailyStatisticsDTO(date);
        
        try {
            // 查询指定日期的所有数据
            QueryWrapper<SensorData> queryWrapper = new QueryWrapper<>();
            queryWrapper.apply("DATE(collect_time) = {0}", date);
            List<SensorData> dataList = sensorDataMapper.selectList(queryWrapper);
            
            // 统计各时段数据
            for (SensorData data : dataList) {
                LocalDateTime collectTime = data.getCollectTime();
                int hour = collectTime.getHour();
                
                if (hour >= 6 && hour < 12) {
                    statistics.setMorningCount(statistics.getMorningCount() + 1);
                } else if (hour >= 12 && hour < 18) {
                    statistics.setNoonCount(statistics.getNoonCount() + 1);
                } else if (hour >= 18 && hour < 24) {
                    statistics.setEveningCount(statistics.getEveningCount() + 1);
                }
                // 0:00-6:00的数据不统计，直接忽略
            }
            
            statistics.setTotalCount((long) dataList.size());
            
            log.info("获取{}的数据统计完成，总条数：{}", date, statistics.getTotalCount());
            
        } catch (Exception e) {
            log.error("获取{}的数据统计时发生异常：{}", date, e.getMessage(), e);
        }
        
        return statistics;
    }
    
    @Override
    public DailyStatisticsDTO getTodayStatistics() {
        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return getDailyStatistics(today);
    }
} 